package com.gmail.yesguxun.tumblr.ui;

import oauth.signpost.OAuth;
import oauth.signpost.OAuthProvider;
import oauth.signpost.basic.DefaultOAuthProvider;
import oauth.signpost.commonshttp.CommonsHttpOAuthConsumer;
import oauth.signpost.commonshttp.CommonsHttpOAuthProvider;
import oauth.signpost.commonshttp.HttpRequestAdapter;
import oauth.signpost.exception.OAuthCommunicationException;
import oauth.signpost.exception.OAuthException;
import oauth.signpost.exception.OAuthNotAuthorizedException;
import oauth.signpost.http.HttpParameters;
import oauth.signpost.http.HttpRequest;
import oauth.signpost.http.HttpResponse;

import android.app.Activity;
import android.os.Bundle;
//import android.os.StrictMode;
import android.util.Log;
import org.json.*;

import com.gmail.yesguxun.tumblr.*;

import com.gmail.yesguxun.tumblr.Constant;

public class TestActivity extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        //StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
        //StrictMode.setThreadPolicy(policy);

        //test1(); 
        test2();
    }
    
    // http://code.google.com/p/oauth-signpost/wiki/TwitterAndSignpost
    public void test2()
    {
    	String comsumerKey = Constant.APP_KEY_CONSUMER_PUBLIC;
    	String consumerSecret = Constant.APP_KEY_CONSUMER_SECRET;
    	CommonsHttpOAuthConsumer consumer = new CommonsHttpOAuthConsumer(comsumerKey, consumerSecret);

    	CommonsHttpOAuthProvider provider = new CommonsHttpOAuthProvider(
                null,  //no request token URL
                //"http://www.tumblr.com/oauth/access_token", 
                "https://www.tumblr.com/oauth/access_token",
                null  //no authorize token
                );
    	
    	try{
    		provider.retreieveAccessTokenXAuth(consumer, "noguxun@gmail.com","1986guxun");
    		OAuth.debugOut("xgu", "get token OK!!");	
    		
    		{
        		String url = "http://api.tumblr.com/v2/user/info";
        		HttpRequest request = provider.createRequestGet(url);
        		
        		consumer.signGet(request);
        		
        		HttpResponse resp = provider.sendRequest(request);
        		 
        		OAuth.debugOut("----------------", "--------------");
                OAuth.debugOut("ReponseCode", "" + resp.getStatusCode());
                OAuth.debugOut("ReponseContent", "" + OAuth.getStringFromStream(resp.getContent()));
    		}
    		  
    		{
                String url = "http://api.tumblr.com/v2/user/dashboard";
                HttpRequest request = provider.createRequestGet(url);
                HttpParameters para = new HttpParameters();
                para.put("limit", "5");
                para.put("type", "photo");
                
                consumer.signGet(request, para);
                
                HttpResponse resp = provider.sendRequest(request);
                String responseContent =  OAuth.getStringFromStream(resp.getContent());
                
                OAuth.debugOut("----------------", "--------------");
                OAuth.debugOut("ReponseCode", "" + resp.getStatusCode());
                OAuth.debugOut("ReponseContent", "" + responseContent);
                
                JSONObject objResp = new JSONObject(responseContent);
                OAuth.debugOut("response", objResp.getJSONObject("response").toString());
                
                JSONArray objPosts = objResp.getJSONObject("response").getJSONArray("posts");
                JSONObject objPost0 = objPosts.getJSONObject(0);
                OAuth.debugOut("posts number", " " + objPosts.length());
                OAuth.debugOut("post 0", " " + objPost0.toString());
                
                String urlPic = objPost0.getJSONArray("photos").getJSONObject(0).getJSONObject("original_size").getString("url");
                OAuth.debugOut("url", urlPic);
    		}
    	}
    	catch(OAuthNotAuthorizedException e){
    		OAuth.debugOut("xgu", "Not Auth " + e.getResponseBody());	    		
    	}
    	catch(OAuthCommunicationException e)
    	{ 
    		OAuth.debugOut("xgu", e.getResponseBody());
    	}
    	catch(Exception e)
    	{
    	    OAuth.debugOut("xgu", "other exception " + e.getMessage());
    	}
    }
    
    // http://j2megroup.blogspot.com/2010/10/xauth-lib-oauth-made-easy.html
    /*
    public void test1()
    {
    	// http://www.tumblr.com/oauth/apps
    	// https://dev.twitter.com/docs/oauth/xauth
    	HttpRequest req = new HttpRequest("https://www.tumblr.com/oauth/access_token");
    	req.setMethod(HttpConnection.POST);
    	
    	// http://www.tumblr.com/oauth/apps
    	String comsumerKey = "zivlYKjOwYwawHsSpupbZcPkbgUggpPrql4hcnxItCmnrgJwBx";
    	String consumerSecret = "sWaheeZjJfeQceAaKI8E0VjwTGkTveyh6x1kLXJBVIF88nEMBZ";
    	XAuthSigner signer = new XAuthSigner(comsumerKey, consumerSecret); 
    	 
    	String userName = "noguxun@gmail.com";
    	String userPassword = "1986guxun";
    	signer.signForAccessToken(req, userName, userPassword);
    	
    	try {
    		HttpResponse resp = req.send();
    		OAuth.debugOut("xgu", "return code" + resp.getCode());
    		if (resp.getCode() == HttpConnection.HTTP_OK) {
    			Token accessToken = Token.parse(resp.getBodyContent());
    			req.close();
    			
    			OAuth.debugOut("xgu", accessToken.getToken());
    			
    		}
    	}catch(IOException e){
    		Log.e("xgu", "no token1");
    		e.printStackTrace();
    	}finally{
    		Log.e("xgu", "no token2");
    		try {
    			req.close();
    		} catch (IOException e) {}
    	}
    }
    //*/
}